package com.tuanbiao.presenter;

import android.text.TextUtils;

import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.abiao.lib_utils.ActivityUtils;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.callback.OnCheckerUpgradeFirmwareCallback;
import com.hzjq.lib.checker.CheckError;
import com.hzjq.lib.checker.ProgressCheckError;
import com.tuanbiao.AppConfig;
import com.tuanbiao.JQBlastConfig;
import com.tuanbiao.base.action.HandlerAction;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.constants.Constants;
import com.tuanbiao.controllers.SplashController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.data.callback.OnProgressCallback;
import com.tuanbiao.dialog.BaseDialog;
import com.tuanbiao.dialog.MessageDialog;
import com.tuanbiao.utils.SPHelper;

import timber.log.Timber;

public class SplashPresenter extends BasePresenter<SplashController.Model, SplashController.View> implements SplashController.Presenter, HandlerAction {

    public SplashPresenter(SplashController.Model model, SplashController.View rootView) {
        super(model, rootView);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    @Override
    public void checkUpdate() {
        if (AppConfig.isNoLogin()) {
            mModel.setModel(true, true);
        }
        JQBlastConfig.initUpload();
        Timber.i("checkUpdate");
        checkStartApp();
//        mModel.getAppVersion(versionResult -> {
//            Timber.i("checkUpdate:" + versionResult.getFirmwareVersion());
//            if (TextUtils.isDigitsOnly(versionResult.getFirmwareVersion()) && Integer.parseInt(versionResult.getFirmwareVersion()) < AppConfig.getBinTagVersion()) {
//                mRootView.showUpgrade();
//            } else {
//                checkStartApp();
//            }
//        });
    }

    @Override
    public void checkStartApp() {
        mModel.startAppCheck(error -> {
            mModel.removeLoginSurplusTime();
            int errorCode = error.getErrorCode();
            String errorMsg = error.getErrorMsg();
            Timber.i(TAG + "#checkStartApp#errorCode:" + errorCode + ",errorMsg" + errorMsg);
            switch (errorCode) {
                case CheckError.CHECK_SUCCESS:
                    mModel.startLoginCheck();
                    BlastKool.Companion.loader().setLoginLimitOutTime(Constants.MaxConfig.LOGIN_LIMIT_TIME);
                    enter(false);
                    //成功
                    break;
                case CheckError.CHECK_UNKONW_ERR:
                    mRootView.showKillDialog(errorMsg);
                    //未知异常
                    break;
                case CheckError.CHECK_SYSTEM_TIME_ERR:
                    //系统时间错误
                    break;

                case CheckError.CHECK_PER_DENIED:
                    //没有权限错误
                    mRootView.showMissingPermissionDialog(false);
                    break;
                case CheckError.CHECK_UPGRADE_STATE:
                    if (error instanceof ProgressCheckError) {
                        mRootView.showProgress(((ProgressCheckError) error).getAction(), ((ProgressCheckError) error).getProgress());
                        Timber.i(TAG + "#checkStartApp#" + ((ProgressCheckError) error).getProgress());
                    } else {
                        mRootView.showUpdate(error.getErrorMsg());
                    }
                    //处于升级中，请勿操作
                    break;
                case CheckError.CHECK_FIRMWARE_NOT_FIND_FILE:
                    //没有在assets中找到可升级的文件
                    mRootView.showKillDialog("没有在assets中找到可升级的文件");
                    break;
                case CheckError.CHECK_FIRMWARE_ERR:
                    //固件通信异常，退出应用，建议重新烧制固件版本
                    mRootView.showKillDialog("通信异常，需要重启应用");
                    break;

                case CheckError.CHECK_NETWORK_ERR:
                    //没有可用的网络
                    break;
                case CheckError.CHECK_LOGIN_OUT_TIME_ERR:
                    mRootView.showMessage(error.getErrorMsg());
                    enter(true);
                    //登录超时
                    break;

                case CheckError.CHECK_UN_LOGIN_TIME_ERR:
                    enter(true);
                    //未登录
                    break;
            }
        }, new OnBaseResultCallback<OnCheckerUpgradeFirmwareCallback>() {
            @Override
            public void onSuccess(OnCheckerUpgradeFirmwareCallback callback) {
                Timber.i("OnCheckerUpgradeFirmwareCallback");
                new MessageDialog.Builder(ActivityUtils.getTopActivity())
                        .setTitle("固件升级")
                        .setMessage("检测到有新版本固件，是否现在升级？")
                        .setListener(new MessageDialog.OnListener() {
                            @Override
                            public void onConfirm(BaseDialog dialog) {
                                callback.doUpgradeFirmware(true);
                            }

                            @Override
                            public void onCancel(BaseDialog dialog) {
                                callback.doUpgradeFirmware(false);
                            }
                        })
                        .setCancelable(false)
                        .show();

            }
        });
    }

    private void enter(boolean login) {
        Timber.i("enter:" + SPHelper.isFirst());
        if (SPHelper.isFirst()) {
            mRootView.startConfig();
            SPHelper.setFirst(false);
        } else {
            mModel.queryMillCode(entity -> {
                if (null != entity && !TextUtils.isEmpty(entity.getModuleMillCode())) {
                    if (login) {
                        mRootView.startLogin();
                    } else {
                        if (mModel.getSettingParams().isStandAloneModel()) mRootView.startMain();
                        else mRootView.startLogin();
                    }
                } else {
                    mRootView.startConfig();
                }
            });
        }

    }

    @Override
    public void upgrade() {
        mModel.upgrade(new OnProgressCallback<Integer>() {

            @Override
            public void onProgress(int progress, String msg) {
                Timber.i("onProgress" + progress + ",msg:" + msg);
                mRootView.showProgressDialog(progress, msg);
            }

            @Override
            public void onFailed(String msg) {
                mRootView.updateFailed(msg);
            }

            @Override
            public void onSuccess(Integer version) {
                Timber.i("upgrade:" + version);
            }

            @Override
            public void onAfter() {
                mRootView.updateFinish();
            }
        });
    }
}
